const shortid = require('shortid')
const modal = require('./modal')
const util = require('./util')
const schema = modal.schema
const config = require('./config')
/**
 * 生成邀请码
 * @returns {Promise}
 */
const generateInviteCode = async () => {
  let inviteCode = shortid.generate()
  /**
   * 检测邀请码是否已经存在，如果存在，则重新生成，否则返回生成的邀请码
   * @param code
   * @returns {Promise.<*>}
   */
  const checkCode = async (code) => {
    const user = modal.user()
    const query = user.query()
    query.equalTo('inviteCode', code)
    if (await query.first()) {
      inviteCode = shortid.generate()
      checkCode(inviteCode)
    } else {
      return inviteCode
    }
  }
  return checkCode(inviteCode)
}
/**
 * 通过邀请码查找父级
 * @param inviteCode
 * @returns {Promise.<*>}
 */
const getParentByInviteCode = async (inviteCode) => {
  const memberSchema = schema.member()
  const query = memberSchema.query()
  query.equalTo('inviteCode', inviteCode)
  return await query.first()
}
/**
 * 获取代理等级及分成比例
 * @param parent
 * @returns {{level: number, shareRate: *}}
 */
const getLevelAndShareRate = (parent) => {
  const level = parent ? Math.min(parent.get('level') + 1, 3) : 1
  const shareRate = config.shareRate[`level${level}`]
  return {
    level,
    shareRate: shareRate.self,
    subShareRate: config.subShareRate
  }
}
/**
 * 保存加盟申请
 */
Parse.Cloud.define('memberApply', async (request, response) => {
  const { name, mobile, wechat, qq, inviteCode, wechatGroupName, wechatGroupCode } = request.params
  if (!name) {
    return response.error('请填写姓名')
  }
  if (!wechat) {
    return response.error('请填写微信号')
  }
  if (!inviteCode) {
    return response.error('无效邀请码')
  }
  if (!util.isMobile(mobile)) {
    return response.error('手机号码不正确')
  }
  const member = schema.member() // 加盟会员
  const group = schema.group()
  const isWechatExist = member.query().equalTo('wechat', wechat)  // 会员中是否已经存在该微信
  const isGroupCodeExist = group.query().equalTo('groupCode', wechatGroupCode)  // 群编号是否已经存在
  const memberChecker = await Promise.all([isWechatExist.first(), isGroupCodeExist.first()])
  if (memberChecker[0]) {
    return response.error('该微信号已经存在，请重新创建')
  }
  if (memberChecker[1]) {
    return response.error('群编码已经存在，请刷新页面重试')
  }
  // 检测邀请码是已否正确
  const parent = await getParentByInviteCode(inviteCode)  // 父级代理
  if (!parent) {
    return response.error('无效邀请码')
  }
  try {
    // 创建用户
    const user = request.user

    const { level, shareRate } = getLevelAndShareRate(parent) // 当前的代理等级及分成比例
    // 创建会员
    const currentMember = await member.save({
      name,
      mobile,
      wechat,
      qq,
      shareRate,
      level,
      inviteCode: await generateInviteCode(),
      status: 0,
      user: user,
      parent,
      sheet: util.generateSheet()
    })
    // 创建群
    await group.save({
      name: wechatGroupName,
      member: currentMember,
      groupCode: wechatGroupCode,
      status: 0
    })
    response.success({
      code: 1
    })
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 获取代理等级及分成比例
 */
Parse.Cloud.define('getLevelAndShareRate', async (request, response) => {
  const { inviteCode } = request.params
  const parent = await getParentByInviteCode(inviteCode)
  if (!parent) {
    response.error('无效邀请码')
  }
  response.success(getLevelAndShareRate(parent))
})
/**
 * 获取群编号
 */
Parse.Cloud.define('getGroupCode', async (request, response) => {
  response.success({
    groupCode: new Date().getTime() + parseInt(Math.random() * 100, 10)
  })
})
/**
 * 获取会员列表
 */
Parse.Cloud.define('getMemberList', async (request, response) => {
  const query = schema.member().query()
  query.equalTo('status', 1)
  const result = await query.find()
  try {
    const members = result.map((item) => {
      return {
        id: item.id,
        name: item.get('name')
      }
    })
    response.success(members)
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 查询加盟申请列表
 */
Parse.Cloud.define('getMembers', async (request, response) => {
  const { currentPage, pageSize, condition } = request.params
  // const { tbkId } = condition ? JSON.parse(condition) : {}
  const memberSchema = schema.member()
  const query = memberSchema.query()
  let memberList = []  // 申请列表

  query.limit(pageSize)
  query.notEqualTo('status', -2) // 不查询已经删除的会员
  query.skip((currentPage - 1) * pageSize)
  query.descending('updatedAt')  // 以更新时间排序
  query.include('tbk')

  if (condition) {
    // 查询指定淘宝客的会员
    const { id, tbkId, status, name } = condition
    if (tbkId) {
      const tbk = schema.tbk()
      tbk.id = tbkId
      query.equalTo('tbk', tbk)
    }
    // 查询指定状态的会员
    if (typeof status === 'number') {
      query.equalTo('status', status)
    }
    // 查询指定ID的会员
    if (id) {
      query.equalTo('objectId', id)
    }
    // 按名称查询
    if (name) {
      query.matches('name', name)
    }
  }

  try {
    const result = await query.find()  // 查找出来的member原始数据

    for (let i = 0, len = result.length; i < len; i++) {
      const item = result[i]
      const groupQuery = schema.group().query()
      const currentMember = util.mapAttributes(item, ['createdAt', 'sheet', 'updateAt', 'name', 'mobile', 'wechat', 'qq', 'shareRate', 'level', 'inviteCode', 'status'])
      currentMember.id = item.id

      const tbk = item.get('tbk')
      // 淘宝客数据
      if (tbk) {
        currentMember.tbkId = tbk.id
        currentMember.tbkUsername = tbk.get('username')
      }
      // 根据member查找注册时创建的群（第一个群）
      groupQuery.equalTo('member', result[i])
      groupQuery.ascending('createdAt')
      const group = await groupQuery.first()
      if (group) {
        currentMember.groupId = group.id
        currentMember.groupName = group.get('name')
        currentMember.groupCode = group.get('groupCode')
      }
      // 查找群数量
      if (condition && condition.searchType === 1) { // 如果需要统计群数据及下级群数量
        // 统计群数量
        currentMember.groupNumber = await util.countGroupNumbers([item.id])
        // 统计下级群数量
        const subMembers = await util.getSubMembers(item, config.deep)  // 所有下级会员
        currentMember.subGroupNumber = await util.countGroupNumbers(subMembers.map((item) => item.id))
      }
      memberList.push(currentMember)
    }

    const count = await query.count()  // 统计数量
    response.success({
      total: count,   // 总数量
      totalPage: Math.ceil(count / pageSize),  // 总页数
      currentPage,   // 当前页
      pageSize,   // 每页数量
      data: memberList   // 查询出来的帖子集
    })
  } catch (err) {
    response.error(err)
  }
})
/**
 * 通过微信号查找member
 */
Parse.Cloud.define('getMemberByWechat', async (request, response) => {
  const user = request.user
  if (!user) {
    return response.error('请先登录')
  }
  const member = schema.member()
  const query = member.query()
  // 查询member
  query.equalTo('user', user).equalTo('status', 1)
  let currentMember = await query.first()
  if (!currentMember) {
    return response.error('没有找到用户')
  }
  // 根据用户查询群编号
  const groupQuery = schema.group().query()
  groupQuery.equalTo('member', currentMember)
  const currentGroup = await groupQuery.first()
  let groupCode
  if (currentGroup) {
    groupCode = currentGroup.get('groupCode')
  }
  // 组合并返回前端需要的数据
  const result = util.mapAttributes(currentMember, ['name', 'mobile', 'wechat', 'qq', 'shareRate', 'level', 'inviteCode'])
  result.groupCode = groupCode
  result.id = currentMember.id
  response.success(result)
})
/**
 * 更改会员状态
 */
Parse.Cloud.define('updateMemberStatus', async (request, response) => {
  const { id, tbkId, status } = request.params
  if (!id) {
    return response.error('请提供需要审核的会员')
  }
  if (typeof status !== 'number') {
    return response.error('状态非法')
  }
  const member = schema.member()
  member.id = id

  if (tbkId) {
    const tbk = schema.tbk()
    tbk.id = tbkId
    member.set('tbk', tbk)
  }
  member.set('status', status)
  try {
    if (status === 1) {
      const account = schema.account()
      account.set('member', member)
      const accountSave = account.save()
      await accountSave
    }
    const memberSave = member.save()
    await memberSave
    response.success({
      code: 1
    })
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 更新会员信息
 */
Parse.Cloud.define('updateMember', async (request, response) => {
  const { id, tbkId, name, mobile, wechat, qq } = request.params
  const member = schema.member()
  let tbk = schema.tbk()
  if (!id) {
    return response.error('请提供需要更新的会员ID')
  }
  if (!name) {
    return response.error('请提供姓名')
  }
  if (!mobile) {
    return response.error('请提供联系方式')
  }
  if (!util.isMobile(mobile)) {
    return response.error('手机号码不正确')
  }
  if (tbkId) {
    tbk.id = tbkId
  } else {
    tbk = ''
  }
  try {
    member.id = id
    await member.save({
      tbk,
      name,
      mobile,
      wechat,
      qq
    })
    response.success({
      code: 1
    })
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 查询群主收益
 */
Parse.Cloud.define('getMemberIncomes', async (request, response) => {
  const { currentPage, pageSize, condition } = request.params
  const query = schema.member().query()

  query.limit(pageSize)
  query.skip((currentPage - 1) * pageSize)
  query.descending('updatedAt')  // 以更新时间排序
  query.include('tbk') // 查找所属淘客
  query.equalTo('status', 1) // 只查找审核通过的会员
  if (condition) {
    const { tbkId, memberId, name } = condition
    // 根据淘客查找
    if (tbkId) {
      const tbk = schema.tbk()
      tbk.id = tbkId
      query.equalTo('tbk', tbk)
    }
    // 根据会员查找
    if (memberId) {
      query.equalTo('objectId', memberId)
    }
    // 根据名称查找
    if (name) {
      query.matches('name', name)
    }
  }
  try {
    const memberFind = query.find()
    const memberCount = query.count()
    const members = await memberFind  // 查找会员
    const count = await memberCount // 统计总数
    const memberList = []
    for (let i = 0, len = members.length; i < len; i++) {
      const currentMember = members[i]
      const memberObject = util.mapAttributes(currentMember, ['name', 'level', 'shareRate', 'status'])
      memberObject.id = currentMember.id
      const tbk = currentMember.get('tbk')
      // 淘客信息
      if (tbk) {
        memberObject.tbkId = tbk.id
        memberObject.tbkUsername = tbk.get('username')
      }
      // 群数量统计
      const subMembers = await util.getSubMembers(currentMember, config.deep)
      const groupCount = util.countGroupNumbers([currentMember.id])
      const subGroupCount = util.countGroupNumbers(subMembers.map((item) => item.id))
      memberObject.groupNumber = await groupCount
      memberObject.subGroupNumber = await subGroupCount
      // 获取本人及下级的群列表
      const getSelfGroups = Parse.Cloud.run('getGroupsByMember', {
        memberId: currentMember.id
      })
      const getSubGroups = Parse.Cloud.run('getSubGroupsByMember', {
        memberId: currentMember.id
      })
      const selfGroups = await getSelfGroups  // 本人的群
      const subGroups = await getSubGroups // 下级的群
      selfGroups.forEach((item) => {
        item.myShareRate = item.memberShareRate  // 本人的佣金
        item.groupOwner = '本人'
        item.groupOwnerType = 'self'
      })
      subGroups.forEach((item) => {
        item.myShareRate = item.parentShareRate  // 下级给本人的佣金
        item.groupOwner = '我的下级代理'
        item.groupOwnerType = 'sub'
      })
      const groups = [].concat(selfGroups, subGroups)  // 合并群
      const orderQuery = schema.order().query()
      orderQuery.equalTo('status', 0)  // 只查找没有核算的订单
      orderQuery.include('group')
      orderQuery.containedIn('group', groups.map((item) => {
        const group = schema.group()
        group.id = item.id
        return group
      }))
      if (condition && condition.orderDate && condition.orderDate[0] && condition.orderDate[1]) {  // 如果有传递时间，则按时间查找
        orderQuery.greaterThanOrEqualTo('orderDate', condition.orderDate[0])
        orderQuery.lessThanOrEqualTo('orderDate', condition.orderDate[1])
      }
      const orders = await orderQuery.find()  // 查找群对应的所有订单
      let selfForecastCommission = 0  // 本人群带来的佣金
      let subForecastCommission = 0 // 下级群带来的佣金
      // 统计每个群所带来的预估收入
      groups.forEach((item) => {
        const groupOrders = orders.filter((order) => {
          const group = order.get('group')
          return group.id === item.id
        })
        const forecastCommission = parseFloat(groupOrders.reduce((prev, current) => {  // 统计总收入
          return prev + current.get('forecastIncome') * item.myShareRate / 100
        }, 0).toFixed(4))
        // 统计自己的群带来的预估收入
        if (item.groupOwnerType === 'self') {
          selfForecastCommission += forecastCommission
        } else {  // 统计下级群带来的预估收入
          subForecastCommission += forecastCommission
        }
        item.forcastCommission = forecastCommission
      })
      memberObject.selfForecastCommission = selfForecastCommission
      memberObject.subForecastCommission = subForecastCommission
      memberObject.totalForecastCommission = selfForecastCommission + subForecastCommission  // 本人群及下级群带来的总预估收入
      memberObject.groups = groups
      memberList.push(memberObject)
    }
    response.success({
      total: count,   // 总数量
      totalPage: Math.ceil(count / pageSize),  // 总页数
      currentPage,   // 当前页
      pageSize,   // 每页数量
      data: memberList   // 查询出来的帖子集
    })
  } catch (err) {
    response.error(err.message)
  }
})